package com.css.fxfzypg.manage.sampling.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.attachment.entity.AttachmentInfoEntity;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.exception.ServiceException;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.constants.FxfzConstants;
import com.css.fxfzypg.manage.sampling.repository.SamplingReqository;
import com.css.fxfzypg.manage.sampling.repository.entity.SamplingEntity;
import com.css.fxfzypg.manage.sampling.repository.entity.StructureFeature;
import com.css.fxfzypg.manage.sampling.service.SamplingService;
import com.css.fxfzypg.manage.sampling.verify.SamplingExcelVerifyHandler;
import com.css.fxfzypg.manage.sampling.vo.SamplingParams;
import com.css.fxfzypg.manage.sampling.vo.SamplingSurveyPointVo;
import com.css.fxfzypg.modules.surveytaskmanage.service.FieldSurveyTaskService;
import com.css.fxfzypg.modules.surveytaskmanage.vo.TaskVo;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import com.css.fxfzypg.zcpt.sys.entity.SUser;
import com.css.fxfzypg.zcpt.sys.service.SUserService;
import com.css.fxfzypg.zcpt.sys.service.SysAreaService;
import com.css.fxfzypg.zcpt.sys.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Service
public class SamplingServiceImpl implements SamplingService {
    @Autowired
    SamplingReqository samplingReqository;

    @Autowired
    SysAreaService sysAreaService;

    @Autowired
    SUserService sUserService;

    @Autowired
    SysRoleService sysRoleService;

    @Autowired
    FieldSurveyTaskService fieldSurveyTaskService;

    @Autowired
    SamplingExcelVerifyHandler samplingExcelVerifyHandler;
    @Autowired
    AttachmentInfoService attachmentInfoService;
    @Value("${image.localDir}")
    private String localDir;

    @Override
    public boolean insertSurvey(SamplingEntity samplingEntity) throws UnsupportedEncodingException {
        String uuid = UUIDGenerator.getUUID();
        samplingEntity.setId(uuid);
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(samplingEntity.getProvince(), "UTF-8"), URLEncoder.encode(samplingEntity.getCity(), "UTF-8"), URLEncoder.encode(samplingEntity.getArea(), "UTF-8"));
        samplingEntity.setProvinceId(divisionIds.split("_")[0]);
        samplingEntity.setCityId(divisionIds.split("_")[1]);
        samplingEntity.setAreaId(divisionIds.split("_")[2]);
        samplingEntity.setCreateTime(new Date());
        samplingEntity.setIsSubmit("0");
        samplingEntity.setDelFlag("0");
        String areaCode = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]).replaceAll("\"", "");//处理字符串,接口返回的数据多了一組引号
        //String geom = samplingReqository.getGeomByCode(areaCode);
        //zyt修改
        String longitude = samplingEntity.getLongitude();
        String latitude = samplingEntity.getLatitude();
        String geom = "POINT(" + longitude + " " + latitude + ")";
        samplingEntity.setGeom(geom);
        return samplingReqository.insertSurvey(samplingEntity);
    }

    @Override
    public boolean saveAndSubmit(SamplingEntity samplingEntity) throws UnsupportedEncodingException {
        String uuid = UUIDGenerator.getUUID();
        samplingEntity.setId(uuid);
        String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(samplingEntity.getProvince(), "UTF-8"), URLEncoder.encode(samplingEntity.getCity(), "UTF-8"), URLEncoder.encode(samplingEntity.getArea(), "UTF-8"));
        samplingEntity.setProvinceId(divisionIds.split("_")[0]);
        samplingEntity.setCityId(divisionIds.split("_")[1]);
        samplingEntity.setAreaId(divisionIds.split("_")[2]);
        samplingEntity.setDelFlag("0");
        samplingEntity.setIsSubmit("1");
        samplingEntity.setCreateTime(new Date());
        samplingEntity.setSubmitter(samplingEntity.getCreateName());
        samplingEntity.setSubmitterId(samplingEntity.getCreateId());
        samplingEntity.setSubmitTime(new Date());
        String areaCode = sysAreaService.getDivisionCodeById(divisionIds.split("_")[2]).replaceAll("\"", "");//处理字符串,接口返回的数据多了一組引号
        //String geom = samplingReqository.getGeomByCode(areaCode);
        //zyt修改
        String longitude = samplingEntity.getLongitude();
        String latitude = samplingEntity.getLatitude();
        String geom = "POINT(" + longitude + " " + latitude + ")";
        samplingEntity.setGeom(geom);
        return samplingReqository.insertSurvey(samplingEntity);
    }

    @Override
    public Map<String, Object> querySubmitOrNot(String submitFlag, String taskCode, int curPage, int pageSize, String userId) {
        return samplingReqository.querySubmitOrNot(submitFlag, taskCode, curPage, pageSize, userId);
    }

    @Override
    public boolean updateIsSubmit(Map<String, String> map) {
        return samplingReqository.updateIsSubmit(map);
    }

    @Override
    public SamplingEntity queryData(String id) {
        SamplingEntity samplingEntity = samplingReqository.queryData(id);
        String userId = PlatformSessionUtils.getUserId();
        String userJson = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(userJson, SUser.class);
        samplingEntity.setSubmitterId(userId);
        if (sUser != null) {
            samplingEntity.setSubmitter(sUser.getUserName());
        } else {
            samplingEntity.setSubmitter("");
        }
        samplingEntity.setSubmitTime(PlatformDateUtils.getCurrentTimestamp());
        return samplingEntity;
    }

    @Override
    public boolean modifyData(SamplingEntity samplingEntity) {
        return samplingReqository.modifyData(samplingEntity);
    }

    @Override
    public boolean modifyAndSubmit(SamplingEntity samplingEntity) {
        samplingEntity.setIsSubmit("1");
        samplingEntity.setSubmitter(samplingEntity.getAssignorName());
        samplingEntity.setSubmitterId(samplingEntity.getAssignorId());
        samplingEntity.setSubmitTime(new Date());
        samplingEntity.setSubmitter(samplingEntity.getAssignorName());
        samplingEntity.setSubmitterId(samplingEntity.getAssignorId());
        return samplingReqository.modifyData(samplingEntity);
    }

    @Override
    public Map<String, Object> querySamplingData(SamplingParams queryParams, int curPage, int pageSize) {
        System.err.println("获取调研点列表数据-------");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        //获取所有任务编号和任务管理员
        List<TaskVo> taskManagers = fieldSurveyTaskService.getTaskManagers();
        //当前登录人(任务管理员)新建的所有任务
        List<String> taskCodeList = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(taskManagers)) {
            for (TaskVo taskVo : taskManagers) {
                String createUser = taskVo.getCreateUser();
                if (createUser.equals(userId)) {
                    taskCodeList.add(taskVo.getTaskNum());
                }
            }
        }
        //国家管理员和业务员有可能 是组长 组员,不可能是省管理员 省业务员
        //省级管理员和业务员有可能 是组长 组员,不可能是国家管理员  国家业务员,也有可能参与了其他省的任务,需要显示省数据和他参与的
        //国家管理员 查看  修改  删除
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            Map<String, Object> map = samplingReqository.querySamplingData(queryParams, curPage, pageSize);
            System.err.println("登录人:" + userId + ",角色是 国家管理员------");
            List<SamplingParams> samplingParams = (List<SamplingParams>) map.get("rows");
            List<SamplingParams> list = new ArrayList<>();
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    samplingData.setFlag("2");
                    list.add(samplingData);
                }

            }
            map.put("rows", list);
            return map;
        }
        //国家业务员  查看 (如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 国家业务员------");
            List<SamplingParams> list = new ArrayList<>();
            Map<String, Object> map = samplingReqository.querySamplingData(queryParams, curPage, pageSize);
            List<SamplingParams> samplingParams = (List<SamplingParams>) map.get("rows");
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    String createId = samplingData.getCreateId();
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(createId)) {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------本人创建");
                        samplingData.setFlag("2");
                    } else if (groupLeaderId.equals(userId)) {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------组长");
                        samplingData.setFlag("2");
                    } else {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------");
                        samplingData.setFlag("1");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
            }
            map.put("rows", list);
            return map;
        }
        //省级管理员(各省查看各省的)  查看  修改  删除
        else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级管理员------");
            //获取该省所有数据和管理员参与的
            Map<String, Object> map = samplingReqository.querySamplingDataByProvince(queryParams, curPage, pageSize, userId, provinceId, taskCodeList);
            List<SamplingParams> list = new ArrayList<>();
            List<SamplingParams> samplingParams = (List<SamplingParams>) map.get("rows");
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    //判断该业务员参与的其他省的  是否为组员
                    List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                    if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                        for (Map<String, Object> map2 : teamMembers) {
                            String teamMember = map2.get("user_id").toString();
                            if (!PlatformObjectUtils.isEmpty(teamMember)) {
                                if (userId.equals(teamMember)) {
                                    System.err.println("组员------");
                                    samplingData.setFlag("1");
                                    break;
                                }
                            }
                        }
                    }
                    //判断该业务员参与的其他省的    或者自己参与的是否为组长或本人
                    String createId = samplingData.getCreateId();
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(createId) || userId.equals(groupLeaderId)) {
                        samplingData.setFlag("2");
                    }
                    //判断是否为自己省
                    if (samplingData.getProvinceId() != null && samplingData.getProvinceId().equals(provinceId)) {
                        samplingData.setFlag("2");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
            }
            map.put("rows", list);
            return map;
        }
        //省级业务员(各省查看各省的)查看   如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级业务员------");
            List<SamplingParams> list = new ArrayList<>();
            //获取该省所有数据和业务员参与的
            Map<String, Object> map = samplingReqository.querySamplingDataByProvince(queryParams, curPage, pageSize, userId, provinceId, taskCodeList);
            List<SamplingParams> samplingParams = (List<SamplingParams>) map.get("rows");
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    //判断是否为自己省
                    if (samplingData.getProvinceId() != null && samplingData.getProvinceId().equals(provinceId)) {
                        samplingData.setFlag("1");
                    }
                    //判断该业务员参与的其他省的  是否为组员
                    List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                    if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                        for (Map<String, Object> map2 : teamMembers) {
                            String teamMember = map2.get("user_id").toString();
                            if (!PlatformObjectUtils.isEmpty(teamMember)) {
                                if (userId.equals(teamMember)) {
                                    System.err.println("登录人:" + userId + ",任务编号:" + samplingData.getTaskCode() + ",该任务中的组员------");
                                    samplingData.setFlag("1");
                                    break;
                                }
                            }
                        }
                    }
                    //判断该业务员参与的其他省的    或者自己参与的是否为组长或本人
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(samplingData.getCreateId()) || userId.equals(groupLeaderId)) {
                        samplingData.setFlag("2");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
            }
            map.put("rows", list);
            return map;
        }
        //本人创建的或者组长:查看 修改 删除,小组组员:查看
        System.err.println("登录人:" + userId + ",无国家/省角色------");
        Map<String, Object> map = samplingReqository.getSamplingDataByTeamMembers(queryParams, curPage, pageSize, userId, taskCodeList);
        List<SamplingParams> list = new ArrayList<>();
        List<SamplingParams> samplingParams = (List<SamplingParams>) map.get("rows");
        if (samplingParams != null && map.size() > 0) {
            for (SamplingParams samplingData : samplingParams) {
                //获取某任务下所有组员
                List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                    for (Map<String, Object> map2 : teamMembers) {
                        String teamMember = map2.get("user_id").toString();
                        if (!PlatformObjectUtils.isEmpty(teamMember)) {
                            if (userId.equals(teamMember)) {
                                System.err.println("登录人:" + userId + ",任务编号:" + samplingData.getTaskCode() + ",该任务中的组员------");
                                samplingData.setFlag("1");
                                break;
                            }
                        }
                    }
                }
                String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                    groupLeaderId = "无组长";
                }
                //本人或者组长
                if (userId.equals(samplingData.getCreateId()) || userId.equals(groupLeaderId)) {
                    System.err.println("登录人:" + userId + ",本人创建或者组长------");
                    samplingData.setFlag("2");
                }
                //任务管理员
                if (taskCodeList.contains(samplingData.getTaskCode())) {
                    samplingData.setFlag("2");
                }
                list.add(samplingData);
            }
        }
        map.put("rows", list);
        return map;
    }

    @Override
    public boolean deleteSampling(String ids) {
        boolean res = true;
        for (String id : ids.split(",")) {
            res = samplingReqository.deleteSampling(id);
            if (res == false) {
                break;
            }
        }
        return res;
    }


    @Override
    public List<SamplingEntity> getDataByUserId(String taskCode, String userId) {
        return samplingReqository.getDataByUserId(taskCode, userId);
    }

    @Override
    public List<SamplingParams> querySamplingMap(SamplingParams queryParams) {
        System.err.println("获取调研点地图数据-------");
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        //获取所有任务编号和任务管理员
        List<TaskVo> taskManagers = fieldSurveyTaskService.getTaskManagers();
        //当前登录人(任务管理员)新建的所有任务
        List<String> taskCodeList = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(taskManagers)) {
            for (TaskVo taskVo : taskManagers) {
                String createUser = taskVo.getCreateUser();
                if (createUser.equals(userId)) {
                    taskCodeList.add(taskVo.getTaskNum());
                }
            }
        }
        //国家管理员和业务员有可能 是组长 组员,不可能是省管理员 省业务员
        //省级管理员和业务员有可能 是组长 组员,不可能是国家管理员  国家业务员,也有可能参与了其他省的任务,需要显示省数据和他参与的
        //国家管理员 查看  修改  删除
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 国家管理员------");
            List<SamplingParams> samplingParams = samplingReqository.querySamplingMap();
            List<SamplingParams> list = new ArrayList<>();
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    samplingData.setFlag("2");
                    list.add(samplingData);
                }
            }
            return list;
        }
        //国家业务员  查看 (如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 国家业务员------");
            List<SamplingParams> list = new ArrayList<>();
            List<SamplingParams> samplingParams = samplingReqository.querySamplingMap();
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    String createId = samplingData.getCreateId();
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(createId)) {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------本人创建");
                        samplingData.setFlag("2");
                    } else if (groupLeaderId.equals(userId)) {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------组长");
                        samplingData.setFlag("2");
                    } else {
                        System.err.println("登录人:" + userId + ",角色是 国家业务员------");
                        samplingData.setFlag("1");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        System.err.println("登录人:" + userId + ",是 " + samplingData.getTaskCode() + "的任务管理员------");
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
            }
            return list;
        }
        //省级管理员(各省查看各省的)  查看  修改  删除
        else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级管理员------");
            //获取该省所有数据和管理员参与的
            List<SamplingParams> samplingParams = samplingReqository.querySamplingDataByProvince(userId, provinceId, taskCodeList);
            List<SamplingParams> list = new ArrayList<>();
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    //判断该业务员参与的其他省的  是否为组员
                    List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                    if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                        for (Map<String, Object> map2 : teamMembers) {
                            String teamMember = map2.get("user_id").toString();
                            if (!PlatformObjectUtils.isEmpty(teamMember)) {
                                if (userId.equals(teamMember)) {
                                    System.err.println("登录人:" + userId + ",任务编号:" + samplingData.getTaskCode() + ",该任务中的组员------");
                                    samplingData.setFlag("1");
                                    break;
                                }
                            }
                        }
                    }
                    //判断该业务员参与的其他省的    或者自己参与的是否为组长或本人
                    String createId = samplingData.getCreateId();
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(createId) || groupLeaderId.equals(createId)) {
                        samplingData.setFlag("2");
                    }
                    //判断是否为自己省
                    if (samplingData.getProvinceId() != null && samplingData.getProvinceId().equals(provinceId)) {
                        samplingData.setFlag("2");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        System.err.println("登录人:" + userId + ",是 " + samplingData.getTaskCode() + "的任务管理员------");
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
                return list;
            }
        }
        //省级业务员(各省查看各省的)查看   如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级业务员------");
            List<SamplingParams> list = new ArrayList<>();
            //获取该省所有数据和业务员参与的
            List<SamplingParams> samplingParams = samplingReqository.querySamplingDataByProvince(userId, provinceId, taskCodeList);
            if (samplingParams != null && samplingParams.size() > 0) {
                for (SamplingParams samplingData : samplingParams) {
                    //判断是否为自己省
                    if (samplingData.getProvinceId() != null && samplingData.getProvinceId().equals(provinceId)) {
                        samplingData.setFlag("1");
                    }
                    //判断该业务员参与的其他省的  是否为组员
                    List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                    if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                        for (Map<String, Object> map2 : teamMembers) {
                            String teamMember = map2.get("user_id").toString();
                            if (!PlatformObjectUtils.isEmpty(teamMember)) {
                                if (userId.equals(teamMember)) {
                                    System.err.println("登录人:" + userId + ",任务编号:" + samplingData.getTaskCode() + ",该任务中的组员------");
                                    samplingData.setFlag("1");
                                    break;
                                }
                            }
                        }
                    }
                    //判断该业务员参与的其他省的    或者自己参与的是否为组长或本人
                    String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                    if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                        groupLeaderId = "无组长";
                    }
                    if (userId.equals(samplingData.getCreateId()) || userId.equals(groupLeaderId)) {
                        samplingData.setFlag("2");
                    }
                    //任务管理员
                    if (taskCodeList.contains(samplingData.getTaskCode())) {
                        System.err.println("登录人:" + userId + ",是 " + samplingData.getTaskCode() + "的任务管理员------");
                        samplingData.setFlag("2");
                    }
                    list.add(samplingData);
                }
                return list;
            }
        }
        //本人创建的或者组长:查看 修改 删除,小组组员:查看
        System.err.println("登录人:" + userId + ",无国家/省角色------");
        List<SamplingParams> samplingParams = samplingReqository.getSamplingDataByTeamMembers(userId, taskCodeList);
        List<SamplingParams> list = new ArrayList<>();
        if (samplingParams != null && samplingParams.size() > 0) {
            for (SamplingParams samplingData : samplingParams) {
                //获取某任务下所有组员
                List<Map<String, Object>> teamMembers = fieldSurveyTaskService.getTeamMembers(samplingData.getTaskCode());//组员
                if (!PlatformObjectUtils.isEmpty(teamMembers) && teamMembers.size() > 0) {
                    for (Map<String, Object> map2 : teamMembers) {
                        String teamMember = map2.get("user_id").toString();
                        if (!PlatformObjectUtils.isEmpty(teamMember)) {
                            if (userId.equals(teamMember)) {
                                System.err.println("登录人:" + userId + ",任务编号:" + samplingData.getTaskCode() + ",该任务中的组员------");
                                samplingData.setFlag("1");
                                break;
                            }
                        }
                    }
                }
                String groupLeaderId = fieldSurveyTaskService.getGroupLeaderId(samplingData.getTaskCode());//组长
                if (PlatformObjectUtils.isEmpty(groupLeaderId)) {
                    groupLeaderId = "无组长";
                }
                //本人或者组长
                if (userId.equals(samplingData.getCreateId()) || userId.equals(groupLeaderId)) {
                    System.err.println("登录人:" + userId + ",本人创建或者组长------");
                    samplingData.setFlag("2");
                }
                list.add(samplingData);
            }
        }
        return list;
    }

    @Override
    public List<SamplingEntity> getSamplingByTaskCode(String taskCode) {
        return samplingReqository.getSamplingByTaskCode(taskCode);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Map<String, Object> uploadSampling(MultipartFile file) throws Exception {
        ImportParams params = new ImportParams();
        params.setImportFields(new String[]{"*任务编号", "*实地调查点名称", "*省", "*市", "*县", "*所属乡镇", "*经度", "*纬度", "*总户数", "*总人口(人)", "*实际常驻人口(人)", "*外出务工人口(人)", "*人口比例%（少年儿童）", "*人口比例%（中青年）", "*人口比例%（老年）", "*交通通达情况", "周边地理环境", "*房屋数量", "*房屋平均间数", "*主要建筑材料", "*房屋类型比例%(高层建筑)", "*房屋类型比例%(钢结构)", "*房屋类型比例%(多层钢筋混凝土结构)", "*房屋类型比例%(砖混结构)", "*房屋类型比例%(砖木结构)", "*房屋类型比例%(土结构)", "*房屋类型比例%(木结构)", "*房屋类型比例%(石结构)", "*房屋类型比例%(其他结构)", "*房屋建造年代比例%(1970年以前)", "*房屋建造年代比例%(1971年-1980年)", "*房屋建造年代比例%(1981年-1990年)", "*房屋建造年代比例%(1991年-2000年)", "*房屋建造年代比例%(2001年-2010年)", "*房屋建造年代比例%(2011年-2015年)", "*房屋建造年代比例%(2016年-2020年)", "*房屋建造年代比例%(2021年及以后)", "*周边是否有学校", "学生数", "教室数", "*周边是否有医院", "医生数", "床位数", "*周边是否有地质灾害", "类型", "规模", "*周边是否有水库", "坝型", "库容", "备注说明"});
        params.setNeedVerify(true);
        params.setVerifyHandler(samplingExcelVerifyHandler);
        boolean res = false;
        Map<String, Object> map = new HashMap<>();
        try {
            String userId = PlatformSessionContext.getUserID();
            String user = sUserService.getSUser(userId);
            SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
            String userName = sUser.getUserName();
            Date date = new Date();
            InputStream inputStream = file.getInputStream();
            ExcelImportResult<SamplingEntity> result = ExcelImportUtil.importExcelMore(inputStream, SamplingEntity.class, params);
            List<SamplingEntity> failList = result.getFailList();
            if (PlatformObjectUtils.isNotEmpty(failList)) {
                StringBuilder errorMsg = new StringBuilder("<font size='5px' color='red'>导入失败：</font>");
                for (SamplingEntity samplingEntity : failList) {
                    errorMsg.append("<font size='4px' ><br>").append("第").append(samplingEntity.getRowNum() + 1).append("行： ").append(samplingEntity.getErrorMsg()).append("</font>");
                }
                map.put("res", res);
                map.put("mess", errorMsg);
                return map;
            }
            List<SamplingEntity> resultData = result.getList();//解析excel
            log.debug("解析excel结果:{}", resultData);
            if (PlatformObjectUtils.isNotEmpty(resultData)) {
                int excelReadRowIndex = 1;
                List<SamplingEntity> list = new ArrayList<>();
                for (SamplingEntity samplingEntity : resultData) {
                    String uuid = UUIDGenerator.getUUID();
                    samplingEntity.setId(uuid);
                    String divisionIds = sysAreaService.getIdByCondition(URLEncoder.encode(samplingEntity.getProvince(), "UTF-8"), URLEncoder.encode(samplingEntity.getCity(), "UTF-8"), URLEncoder.encode(samplingEntity.getArea(), "UTF-8"));
                    if (org.apache.commons.lang3.StringUtils.isBlank(divisionIds)) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-省(" + samplingEntity.getProvince().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    samplingEntity.setProvinceId(divisionIds.split("_")[0]);
                    if (divisionIds.split("_").length == 1) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-市(" + samplingEntity.getCity().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    samplingEntity.setCityId(divisionIds.split("_")[1]);
                    if (divisionIds.split("_").length == 2) {
                        throw new ServiceException("第" + excelReadRowIndex + "行的建筑地点-县(" + samplingEntity.getArea().trim() + ")有误，请填写准确的名称，例如：北京市");
                    }
                    samplingEntity.setAreaId(divisionIds.split("_")[2]);
//                    samplingEntity.setProvinceId(divisionIds.split("_")[0]);
//                    samplingEntity.setCityId(divisionIds.split("_")[1]);
//                    samplingEntity.setAreaId(divisionIds.split("_")[2]);
                    samplingEntity.setTaskName(fieldSurveyTaskService.getTaskNameByTaskNum(samplingEntity.getTaskCode()));
                    samplingEntity.setIsSubmit("1");
                    samplingEntity.setDelFlag("0");
                    samplingEntity.setCreateName(userName);
                    samplingEntity.setCreateId(userId);
                    samplingEntity.setCreateTime(date);
                    samplingEntity.setSubmitter(userName);
                    samplingEntity.setSubmitterId(userId);
                    samplingEntity.setSubmitTime(date);
                    String longitude = samplingEntity.getLongitude();
                    String latitude = samplingEntity.getLatitude();
                    String geom = "POINT(" + longitude + " " + latitude + ")";
                    samplingEntity.setGeom(geom);
                    list.add(samplingEntity);
                }
                if (!PlatformObjectUtils.isEmpty(list)) {
                    int currRow = 1;
                    for (SamplingEntity entity : list) {
                        if (!samplingReqository.existByFieldSurveyNameAndTaskCode(entity.getFieldSurveyName(), entity.getTaskCode())) {
                            res = samplingReqository.insertSurvey(entity);//保存
                            if (!res) {
                                break;
                            }
                        } else {
                            throw new ServiceException("第" + currRow + "行，任务编号为：" + entity.getTaskCode() + "的任务下已经存在实地调查点名称为：" + entity.getFieldSurveyName() + "的数据了");
                        }
                        currRow++;
                    }
                }
            }
        } catch (Exception e) {
            if (e.getMessage().contains("不是合法")) {
                map.put("mess", "上传失败! 上传的文件模板有误,请检查表头是否改动！");
            }
            throw e;
        }
        map.put("res", res);
        return map;

    }

    @Override
    public void exportSampling(HttpServletResponse response, SamplingParams queryParams) {
      /*  Map<String, Object> map = this.querySamplingData(queryParams, 1, 99999999);
        List<SamplingParams> samplingEntities = (List<SamplingParams>)map.get("rows");*/
        String userId = PlatformSessionContext.getUserID();
        String user = sUserService.getSUser(userId);
        SUser sUser = CreateGson.createGson().fromJson(user, SUser.class);
        String role = sysRoleService.getRoleByUserId(userId);
        List<Map> maps = JSONObject.parseArray(role, Map.class);//一个人可能有多个角色
        //当前登录人所有的角色
        StringBuilder roles = new StringBuilder();
        for (int i = 0; i < maps.size(); i++) {
            Map map = maps.get(i);
            roles.append(map.get("roleCode") + ",");
        }
        String allRole = roles.toString();
        String provinceId = sUser.getProvinceId();//省id
        //获取所有任务编号和任务管理员
        List<TaskVo> taskManagers = fieldSurveyTaskService.getTaskManagers();
        //当前登录人(任务管理员)新建的所有任务
        List<String> taskCodeList = new ArrayList<>();
        if (!PlatformObjectUtils.isEmpty(taskManagers)) {
            for (TaskVo taskVo : taskManagers) {
                String createUser = taskVo.getCreateUser();
                if (createUser.equals(userId)) {
                    taskCodeList.add(taskVo.getTaskNum());
                }
            }
        }
        //国家管理员和业务员有可能 是组长 组员,不可能是省管理员 省业务员
        //省级管理员和业务员有可能 是组长 组员,不可能是国家管理员  国家业务员,也有可能参与了其他省的任务,需要显示省数据和他参与的
        //国家管理员 查看  修改  删除
        List<SamplingEntity> samplingEntities = null;
        if (allRole.contains(FxfzConstants.YPG_COUN_GL_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 国家管理员------");
            samplingEntities = samplingReqository.querySampling(queryParams);

        }
        //国家业务员  查看 (如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_COUN_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 国家业务员------");
            samplingEntities = samplingReqository.querySampling(queryParams);

        }
        //省级管理员(各省查看各省的)  查看  修改  删除
        else if (allRole.contains(FxfzConstants.YPG_PRI_GL_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级管理员------");
            //获取该省所有数据和管理员参与的
            samplingEntities = samplingReqository.querySamplingByProvince(queryParams, userId, provinceId, taskCodeList);
        }
        //省级业务员(各省查看各省的)查看   如果是本人创建的或者组长需要加修改删除)
        else if (allRole.contains(FxfzConstants.YPG_PRI_YW_ROLE)) {
            System.err.println("登录人:" + userId + ",角色是 省级业务员------");
            //获取该省所有数据和业务员参与的
            samplingEntities = samplingReqository.querySamplingByProvince(queryParams, userId, provinceId, taskCodeList);
        } else {
            //本人创建的或者组长:查看 修改 删除,小组组员:查看
            System.err.println("登录人:" + userId + ",无国家/省角色------");
            samplingEntities = samplingReqository.querySamplingDataByTeamMembers(queryParams, userId, taskCodeList);
        }
        if (samplingEntities == null || samplingEntities.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        //去重
//        List<SamplingEntity> samplingEntityList = duplicateRemoval(samplingEntities);

        try {
          //  ExportUtil.createExcel(response, samplingEntities, "抽样调查点概况信息", SamplingParams.class);

            EasyPoiExcelUtil.exportExcel(samplingEntities, null, "sheet", SamplingEntity.class, "抽样调查点概况信息", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public SamplingEntity getNearestSamplingAPP(String longitude, String latitude, String taskCode) {
        if (PlatformObjectUtils.isEmpty(longitude) || PlatformObjectUtils.isEmpty(latitude) || PlatformObjectUtils.isEmpty(taskCode)) {
            return null;
        }
        String lonlat = longitude + " " + latitude;
        return samplingReqository.getNearestSamplingAPP(lonlat, taskCode);
    }

    @Override
    public List<Map<String, Object>> getFieldSurveyNameByTaskCode(String taskCode) {
        return samplingReqository.getFieldSurveyNameByTaskCode(taskCode);
    }

    private List<SamplingEntity> duplicateRemoval(List<SamplingEntity> list) {
        Set set = new HashSet();
        List<SamplingEntity> newList = new ArrayList<>();
        for (Iterator iter = list.iterator(); iter.hasNext(); ) {
            Object next = iter.next();
            if (set.add(next)) {
                newList.add((SamplingEntity) next);
            }
        }
        list.clear();
        list.addAll(newList);
        return list;
    }

    @Override
    public boolean saveStructureFeature(StructureFeature structureFeature) {
        return samplingReqository.saveStructureFeature(structureFeature);
    }

    @Override
    public RestResponse getSamplingSurveyPoint(SamplingSurveyPointVo samplingSurveyPointVo, HttpServletRequest request) {
        try {
            int page = Integer.valueOf(request.getParameter(PlatformPageUtils.CUR_PAGE));
            int size = Integer.valueOf(request.getParameter(PlatformPageUtils.PAGE_SIZE));
            return RestResponse.succeed(samplingReqository.getSamplingSurveyPoint(samplingSurveyPointVo, page, size));
        } catch (Exception e) {
            String errorMessage = "查询失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    public void savePie(String id, String typePie, String yearsPie) {
        MultipartFile typeImage = Base64DecodeMultipartFile.base64Convert(typePie);
        MultipartFile yearsImage = Base64DecodeMultipartFile.base64Convert(yearsPie);
        String typeImageFileId = null;
        String yearsImageFileId = null;
        try {
            typeImageFileId = getImageFileId(typeImage);
            yearsImageFileId = getImageFileId(yearsImage);
        } catch (IOException e) {
            e.printStackTrace();
        }
        samplingReqository.update(id, typeImageFileId, yearsImageFileId);
    }

    @Override
    public List<SamplingEntity> getByTaskCodeAndProvinceId(String taskNum, String provinceId) {
        return samplingReqository.getByTaskCodeAndProvinceId(taskNum, provinceId);
    }

    @Override
    public Integer countByTaskCodeAndProvinceId(String taskNum, String provinceId) {
        return samplingReqository.countByTaskCodeAndProvinceId(taskNum, provinceId);
    }

    @Override
    public Integer countCommitByTaskCodeAndProvinceId(String taskNum, String provinceId) {
        return samplingReqository.countCommitByTaskCodeAndProvinceId(taskNum, provinceId);
    }

    private String getImageFileId(MultipartFile image) throws IOException {
        //获取文件名称
        String fileName = image.getOriginalFilename();
        //获取文件上传的本地路径
        String dateDir = new SimpleDateFormat("/yyyy/MM/dd").format(new Date());
        String savePath = localDir + dateDir;
        //构建文件
        assert fileName != null;
        //上传文件
        String realFileName = uploadFile(fileName, savePath, image);
        //构建实体类
        AttachmentInfoEntity attachmentInfoEntity = buildAttachment(fileName, dateDir, realFileName);
        List<AttachmentInfoEntity> list = new ArrayList<>();
        list.add(attachmentInfoEntity);
        attachmentInfoService.save(list);
        return attachmentInfoEntity.getAttachId();
    }

    private AttachmentInfoEntity buildAttachment(String fileName, String dateDir, String realFileName) {
        AttachmentInfoEntity attachmentInfoEntity = new AttachmentInfoEntity();
        attachmentInfoEntity.setAttachId(StringUtils.buildPrimaryId());
        attachmentInfoEntity.setAttachName(fileName);
        attachmentInfoEntity.setAttachPath(dateDir + "/" + realFileName);
        attachmentInfoEntity.setFileDirId(localDir);
        attachmentInfoEntity.setIsValid("1");
        attachmentInfoEntity.setIsCompleted("1");
        return attachmentInfoEntity;
    }

    private String uploadFile(String fileName, String savePath, MultipartFile multipartFile) throws IOException {
        // 获取文件的后缀名
        assert fileName != null;
        String preFileName = fileName.substring(0, fileName.lastIndexOf("."));
        // .jpg  .pdf  .txt  .docs
        String fileType = fileName.substring(fileName.lastIndexOf("."));
        // 拼文件名  真实的文件名称
        String realFileName = preFileName + "_" + System.currentTimeMillis() + fileType;
        //判断文件夹是否存在如果不存在则创建
        if (!new File(savePath).exists()) {
            new File(savePath).mkdirs();
        }
        File file = new File(savePath, realFileName);
        multipartFile.transferTo(file);
        return realFileName;
    }
}
